<template>
    <t-button theme="default" @click="handleOpenDialog">
      查看结算表
    </t-button>
    <t-dialog 
      v-model:visible="showExpenseTableDialog" 
      :destroy-on-close="true"
      mode="full-screen"
      :footer="null"
    >
      <t-form ref="formRef" :data="expenseData" reset-type="initial" @submit="handleSave">
        
      
      <div class="excel-container" style="overflow-y: auto;">
        <table class="excel-table" border="1" cellpadding="4" cellspacing="0">
          <tbody>
          <!-- 基础信息区 -->
          <tr>
            <td class="excel-header" colspan="2">客户</td>
            <td class="excel-header" colspan="2">
              {{ expenseData.customer }}</td>
            <td class="excel-header" colspan="2">地址:</td>
            <td class="excel-cell" colspan="8">{{ expenseData.address }}</td>
            <td class="excel-header" colspan="2">设计师</td>
            <td class="excel-cell" colspan="2">{{ expenseData.designer }}</td>
            <td class="excel-header" colspan="2">工期：</td>
            <td class="excel-cell" colspan="4">{{ expenseData.duration }}</td>
          </tr>
          
          <tr>
            <td class="excel-header" colspan="2">合同总价</td>
            <td class="excel-cell" colspan="2">
              {{ expenseData.contractTotal }}
            </td>
            <td class="excel-header" colspan="4">一期款</td>
            <td class="excel-cell" colspan="2">
              {{ expenseData.contractTotal*0.4 }}
            </td>
            <td class="excel-header" colspan="2">二期款</td>
            <td class="excel-cell" colspan="2">
              {{ expenseData.contractTotal*0.4 }}
            </td>
            <td class="excel-header" colspan="2">三期款</td>
            <td class="excel-cell" colspan="2">
              {{ expenseData.contractTotal*0.2 }}
            </td>
            <td class="excel-header" colspan="2">尾款</td>
            <td class="excel-cell" colspan="2">
              <t-input-number v-model:value="expenseData.balancePayment" :min="0" size="small"/>
            </td>
          </tr>

          <tr>
            <td class="excel-header" colspan="2">项目经理发包</td>
            <td class="excel-cell" colspan="2">
              <t-input-number v-model:value="expenseData.projectManagerDispatch" :min="0" size="small"/>
            </td>
            <td class="excel-header" colspan="2">套餐面积</td>
            <td class="excel-cell" colspan="2">
              <t-input-number v-model:value="expenseData.packageArea" :min="0" size="small"/>
            </td>
            <td class="excel-header" colspan="2">超出套餐面积</td>
            <td class="excel-cell" colspan="2">
              <t-input-number v-model:value="expenseData.exceedPackageArea" :min="0" size="small"/>
            </td>
            <td class="excel-header" colspan="4">卫生间包补贴及远程费补贴</td>
            <td class="excel-cell" colspan="2">
              <t-input-number v-model:value="expenseData.remoteSubsidy" :min="0" size="small"/>
            </td>
            <td class="excel-header" colspan="2">套餐发包小计</td>
            <td class="excel-cell" colspan="2">
              <t-input-number v-model:value="expenseData.packageContractSubtotal" :min="0" size="small"/>
            </td>
          </tr>

          <tr>
            <td class="excel-header" colspan="2">基础超出部分</td>
            <td class="excel-cell" colspan="2">
              <t-input-number v-model:value="expenseData.excessPortion" :min="0" size="small" :step="0.01" :precision="2"/>
            </td>
            <td class="excel-header" colspan="2">发包比例</td>
            <td class="excel-cell" colspan="2">
              <t-input-number v-model:value="expenseData.dispatchRatio" :min="0" size="small" :step="0.01" :precision="2"/>
            </td>
            <td class="excel-cell" colspan="6"></td>
            <td class="excel-header" colspan="6">基础超出发包小计</td>
            <td class="excel-cell" colspan="2">
              <t-input-number v-model:value="expenseData.basicExceedContractSubtotal" :min="0" size="small"/>
            </td>
          </tr>

          <tr>
            <td class="excel-header" colspan="20">发包价合计</td>
            <td class="excel-cell" colspan="2">
              <t-input-number v-model:value="expenseData.contractTotalAmount" :min="0" size="small"/>
            </td>
          </tr>

          <!-- 整装包含项目 -->
          <tr>
            <td class="excel-header" colspan="2" rowspan="61">整装包含项目</td>
            <td class="excel-header" colspan="2" rowspan="2">付款阶段</td>
            <td class="excel-header" colspan="4" rowspan="2">项目类别</td>
            <td class="excel-header" colspan="6">人工费</td>
            <td class="excel-header" colspan="6">辅料</td>
            <td class="excel-header" colspan="2" rowspan="2">阶段合计</td>
          </tr>
          <tr>
            <td class="excel-header" colspan="2">套餐金额</td>
            <td class="excel-header" colspan="4">实际支出</td>
            <td class="excel-header" colspan="2">项目类别</td>
            <td class="excel-header" colspan="4">实际支付</td>
          </tr>

          <!-- 基础项目 - 人工和辅料在同一行 -->
          <tr 
            v-for="(item, index) in expenseData.basicItems" 
            :key="index"
            class="hover-row"
            @mouseenter="setHoveredRow(index, 'labor')"
            @mouseleave="clearHoveredRow"
          >
            <td class="excel-header" v-if="index === 0" :rowspan="expenseData.basicItems.length + 1" colspan="2">基础</td>
            <td class="excel-header" colspan="4">
              <div class="cell-with-actions">
                <t-input v-model="item.itemName" size="small"></t-input>
                <div v-if="hoveredRowIndex === index && hoveredRowType === 'labor'" class="row-actions">
                  <t-button size="small" theme="primary" @click="addRow('basicItems', index)">+</t-button>
                  <t-button size="small" theme="danger" @click="removeRow('basicItems', index)" :disabled="expenseData.basicItems.length <= 1">-</t-button>
                </div>
              </div>
            </td>
            <!-- 人工费部分 -->
            <td class="excel-cell" colspan="2">
              <t-input-number v-model:value="item.packageAmount" :min="0" size="small"/>
            </td>
            <td class="excel-cell" colspan="4">
              <t-input-number v-model:value="item.actualLabor" :min="0" size="small"/>
            </td>
            <!-- 辅料部分 -->
            <td class="excel-cell" colspan="2">
              <t-input v-model:value="item.materialPackageAmount" size="small" placeholder="项目类别"/>
            </td>
            <td class="excel-cell" colspan="4">
              <t-input-number v-model:value="item.actualMaterial" :min="0" size="small"/>
            </td>
            <td class="excel-cell" v-if="index === 0" colspan="2" :rowspan="expenseData.basicItems.length + 1">
              <t-input-number v-model:value="expenseData.basicStageTotal" :min="0" size="small"/>
            </td>
          </tr>

          <!-- 阶段合计 -->
          <tr>
            <td class="excel-header" colspan="4">阶段合计</td>
            <td class="excel-cell" colspan="6">
              <t-input-number v-model:value="expenseData.basicStageLaborTotal" :min="0" size="small"/>
            </td>
            <td class="excel-cell" colspan="6">
              <t-input-number v-model:value="expenseData.basicStageMaterialTotal" :min="0" size="small"/>
            </td>
          </tr>

          <!-- 主材部分 -->
          <tr 
            v-for="(item, index) in expenseData.basicItems2" 
            :key="'main'+index"
            class="hover-row"
            @mouseenter="setHoveredRow(index, 'main')"
            @mouseleave="clearHoveredRow"
          >
            <td class="excel-header" v-if="index === 0" :rowspan="expenseData.basicItems2.length" colspan="2">主材</td>
            <td class="excel-cell" colspan="4">
              <div class="cell-with-actions">
                <t-input v-model="item.itemName" size="small" placeholder="项目名称"></t-input>
                <div v-if="hoveredRowIndex === index && hoveredRowType === 'main'" class="row-actions">
                  <t-button size="small" theme="primary" @click="addRow('basicItems2', index)">+</t-button>
                  <t-button size="small" theme="danger" @click="removeRow('basicItems2', index)" :disabled="expenseData.basicItems2.length <= 1">-</t-button>
                </div>
              </div>
            </td>
            <td class="excel-cell" colspan="12">
              <t-input-number v-model:value="item.amount" :min="0" size="small"/>
            </td>
            <td class="excel-cell" colspan="2" v-if="index === 0" :rowspan="expenseData.basicItems2.length">
              <t-input-number v-model:value="expenseData.mainMaterialTotal" :min="0" size="small"/>
            </td>
          </tr>
          

          <!-- 优惠赠送部分 -->
          <tr 
            v-for="(item, index) in expenseData.basicItems3" 
            :key="'gift'+index"
            class="hover-row"
            @mouseenter="setHoveredRow(index, 'gift')"
            @mouseleave="clearHoveredRow"
          >
            <td class="excel-header" v-if="index === 0" :rowspan="expenseData.basicItems3.length" colspan="2">优惠赠送</td>
            <td class="excel-cell" colspan="4">
              <div class="cell-with-actions">
                <t-input v-model="item.itemName" size="small" placeholder="项目名称"></t-input>
                <div v-if="hoveredRowIndex === index && hoveredRowType === 'gift'" class="row-actions">
                  <t-button size="small" theme="primary" @click="addRow('basicItems3', index)">+</t-button>
                  <t-button size="small" theme="danger" @click="removeRow('basicItems3', index)" :disabled="expenseData.basicItems3.length <= 1">-</t-button>
                </div>
              </div>
            </td>
            <td class="excel-cell" colspan="12">
              <t-input-number v-model:value="item.amount" :min="0" size="small"/>
            </td>
            <td class="excel-cell" colspan="2" v-if="index === 0" :rowspan="expenseData.basicItems3.length">
              <t-input-number v-model:value="expenseData.discountTotal" :min="0" size="small"/>
            </td>
          </tr>
          

          <!-- 洽商部分 -->
          <tr>
            <td class="excel-header" :rowspan="expenseData.basicItems4.length+1" colspan="2">洽商部分</td>
            <td class="excel-cell" colspan="10">
              项目名称
            </td>
            <td class="excel-cell" colspan="2">
              类型
            </td>
            <td class="excel-cell" colspan="4">
              金额
            </td>
            <td class="excel-cell" colspan="2" :rowspan="expenseData.basicItems4.length+1">
              <t-input-number v-model:value="expenseData.negotiationTotal" :min="0" size="small"/>
            </td>
          </tr>
          <tr 
            v-for="(item, index) in expenseData.basicItems4" 
            :key="'qs'+index"
            class="hover-row"
            @mouseenter="setHoveredRow(index, 'negotiation')"
            @mouseleave="clearHoveredRow"
          >
            <td class="excel-cell" colspan="10">
              <div class="cell-with-actions">
                <t-input v-model="item.itemName" size="small" placeholder="项目名称"></t-input>
                <div v-if="hoveredRowIndex === index && hoveredRowType === 'negotiation'" class="row-actions">
                  <t-button size="small" theme="primary" @click="addRow('basicItems4', index)">+</t-button>
                  <t-button size="small" theme="danger" @click="removeRow('basicItems4', index)" :disabled="expenseData.basicItems4.length <= 1">-</t-button>
                </div>
              </div>
            </td>
            <td class="excel-cell" colspan="2">
              <t-input v-model="item.type" size="small" placeholder="类型"></t-input>
            </td>
            <td class="excel-cell" colspan="4">
              <t-input-number v-model:value="item.amount" :min="0" size="small"/>
            </td>
          </tr>
          

          <!-- 底部汇总 -->
          <tr>
            <td class="excel-header" colspan="16">监理创业者利润小计</td>
            <td class="excel-cell" colspan="6">
              <t-input-number v-model:value="expenseData.supervisorProfitSubtotal" :min="0" size="small"/>
            </td>
          </tr>
          <tr>
            <td class="excel-header" colspan="16">工地质保金</td>
            <td class="excel-cell" colspan="6">
              <t-input-number v-model:value="expenseData.marginDeposit" :min="0" size="small"/>
            </td>
          </tr>
          <tr>
            <td class="excel-header" colspan="16">扣掉阶段已付款后应付(扣质保金后）</td>
            <td class="excel-cell" colspan="6">
              <t-input-number v-model:value="expenseData.finalPayableAmount" :min="0" size="small"/>
            </td>
          </tr>
          </tbody>
        </table>
        
        <div class="dialog-footer" style="margin-top: 20px; text-align: center;">
          <t-button theme="primary" @click="formRef?.submit">保存</t-button>
          <t-button theme="default" @click="showExpenseTableDialog = false" style="margin-left: 10px;">取消</t-button>
        </div>
      </div>
      </t-form>
    </t-dialog>
  
</template>

<script setup lang="ts">
import { onMounted, ref, useTemplateRef } from 'vue';
import { FormInstanceFunctions, MessagePlugin, SubmitContext } from 'tdesign-vue-next';
import { getSettlement, saveSettlement } from '@/api/project/details';

// 定义 props
const props = defineProps({
  orderId: {
    type: String,
    require: true,
  },
});

// 初始化基础项目数据 - 人工和辅料在同一行
const initializeBasicItems = () => {
  const defaultItems = [
    '拆除', '成品保护', '砌墙', '砌墙修补', '二次进场', '砌墙卫生费', 
    '水电前期', '水电项目', '水电项目补贴', '开槽卫生费', '水电完工卫生费',
    '瓦工', '二次进场', '防水', '包管', '瓦工卫生费', '木作', '木作卫生费',
    '油漆', '油漆', '油漆卫生费', '安装卫生费', '水电后期', '保洁',
    '材料搬运费及垃圾清运费（无电梯）', '卫生清理费', '材料搬运费', '垃圾清理费'
  ];
  
  return defaultItems.map(itemName => ({
    itemName,
    packageAmount: 0,
    actualLabor: 0,
    materialPackageAmount: '',
    actualMaterial: 0
  }));
};

// 初始化主材数据
const initializeMainMaterials = () => {
  // 主材只有一行空白数据
  return [{
    itemName: '',
    amount: 0
  }];
};

// 初始化优惠赠送数据
const initializeDiscountItems = () => {
  // 优惠赠送只有一行空白数据
  return [{
    itemName: '',
    amount: 0
  }];
};

// 初始化洽商部分数据
const initializeNegotiationItems = () => {
  // 洽商部分只有一行空白数据
  return [{
    itemName: '',
    type: '',
    amount: 0
  }];
};

const expenseData = ref({
  // 基础信息
  customer: '',
  address: '',
  designer: '',
  duration: '',
  
  // 合同款项
  contractTotal: 0,
  oneMoney: 0,
  twoMoney: 0,
  threeMoney: 0,
  balancePayment: 0,
  
  // 发包信息
  projectManagerDispatch: 490,
  packageArea: 60,
  remoteSubsidy: 1504,
  packageContractSubtotal: 30904,
  managerContract2: 465,
  exceedPackageArea: 0,
  excessPortion: 0.00,
  dispatchRatio: 65.00,
  basicExceedContractSubtotal: 0,
  contractTotalAmount: 30904,
  
  // 基础项目 - 人工和辅料在同一行
  basicItems: initializeBasicItems(),
  basicStageTotal: 0,
  basicStageLaborTotal: 0,
  basicStageMaterialTotal: 0,
  
  // 主材
  basicItems2: initializeMainMaterials(),
  mainMaterialTotal: 0,
  
  // 优惠赠送
  basicItems3: initializeDiscountItems(),
  discountTotal: 0,
  
  // 洽商部分
  basicItems4: initializeNegotiationItems(),
  negotiationTotal: 0,
  
  // 汇总
  supervisorProfitSubtotal: 30904.00,
  marginDeposit: 0,
  finalPayableAmount: 30904.00,
});

const showExpenseTableDialog = ref(false);
const hoveredRowIndex = ref(-1);
const hoveredRowType = ref(''); // 'labor', 'main', 'gift', 'negotiation'

// 设置悬停的行
const setHoveredRow = (index: number, type: string) => {
  hoveredRowIndex.value = index;
  hoveredRowType.value = type;
};

// 清除悬停状态
const clearHoveredRow = () => {
  hoveredRowIndex.value = -1;
  hoveredRowType.value = '';
};

// 通用的添加行方法
const addRow = (arrayName: string, index: number) => {
  const emptyRow = getEmptyRow(arrayName);
  expenseData.value[arrayName].splice(index + 1, 0, emptyRow);
};

// 通用的删除行方法
const removeRow = (arrayName: string, index: number) => {
  if (expenseData.value[arrayName].length > 1) {
    expenseData.value[arrayName].splice(index, 1);
  }
};

// 根据数组名称获取空行模板
const getEmptyRow = (arrayName: string) => {
  switch (arrayName) {
    case 'basicItems':
      return {
        itemName: '',
        packageAmount: 0,
        actualLabor: 0,
        materialPackageAmount: '',
        actualMaterial: 0
      };
    case 'basicItems2':
    case 'basicItems3':
      return {
        itemName: '',
        amount: 0
      };
    case 'basicItems4':
      return {
        itemName: '',
        type: '',
        amount: 0
      };
    default:
      return {};
  }
};

const calculateTotals = () => {
  // 计算主材总计
  expenseData.value.mainMaterialTotal = expenseData.value.basicItems2.reduce(
    (sum, item) => sum + (item.amount || 0), 0
  );
  
  // 计算优惠赠送总计
  expenseData.value.discountTotal = expenseData.value.basicItems3.reduce(
    (sum, item) => sum + (item.amount || 0), 0
  );
  
  // 计算洽商部分总计
  expenseData.value.negotiationTotal = expenseData.value.basicItems4.reduce(
    (sum, item) => sum + (item.amount || 0), 0
  );
  
  // 计算基础项目人工费总计
  expenseData.value.basicStageLaborTotal = expenseData.value.basicItems.reduce(
    (sum, item) => sum + (item.actualLabor || 0), 0
  );
  
  // 计算基础项目辅料费总计
  expenseData.value.basicStageMaterialTotal = expenseData.value.basicItems.reduce(
    (sum, item) => sum + (item.actualMaterial || 0), 0
  );
  
  // 计算基础项目阶段总计
  expenseData.value.basicStageTotal = expenseData.value.basicStageLaborTotal + expenseData.value.basicStageMaterialTotal;
};

const handleInitExcel = () => {
  getSettlement({orderId:props.orderId}).then(res=> {
    if(res.basicItems.length===0) {
        // 基础项目 - 人工和辅料
      res.basicItems= initializeBasicItems()
    }
    if(!res.basicItems2 || res.basicItems2.length===0) {
       // 主材
      res.basicItems2= initializeMainMaterials()
    }
    if(!res.basicItems3 || res.basicItems3.length===0) {
        // 优惠赠送
      res.basicItems3= initializeDiscountItems()
    }
    if(!res.basicItems4 || res.basicItems4.length===0) {
      // 洽商部分
      res.basicItems4= initializeNegotiationItems()
    }
    expenseData.value = res

  })
}
const handleOpenDialog = () => {
  handleInitExcel()
  showExpenseTableDialog.value = true
}
const formRef = useTemplateRef<FormInstanceFunctions>('formRef');
const handleSave = ({ validateResult }: SubmitContext) => {
  if (validateResult !== true) return;
  let params = {
    ...expenseData.value,
  };
 
  // 计算各项总计
  calculateTotals();
  console.log(expenseData.value);
  
  // saveSettlement(params).then(res => {
  //   showExpenseTableDialog.value = false;
  // }).catch(({ message }) => {
  //     MessagePlugin.error(message);
  //   })
 
};
const handleReset = () => {
  formRef.value.reset();
};
</script>

<style scoped>
.excel-table {
  width: 100%;
  border-collapse: collapse;
  font-family: "Microsoft YaHei", Arial, sans-serif;
  font-size: 12px;
  color: #333;
}
.excel-header {
  font-weight: bold;
  text-align: center;
  vertical-align: middle;
  border: 1px solid #000;
  padding: 4px 8px;
}
.excel-cell {
  text-align: center;
  vertical-align: middle;
  border: 1px solid #000;
  white-space: normal;
  word-break: break-all;
  padding: 2px 4px;
}
.excel-container {
  padding: 10px;
  background-color: #fff;
  max-height: 90vh;
  overflow: auto;
}

.hover-row:hover {
  background-color: #f5f5f5;
}

.cell-with-actions {
  position: relative;
  display: flex;
  align-items: center;
  gap: 8px;
}

.row-actions {
  display: flex;
  gap: 4px;
  margin-left: 8px;
}

:deep(.t-input-number) {
  --td-input-height: 24px;
  --td-input-font-size: 12px;
}
:deep(.t-input) {
  --td-input-height: 24px;
  --td-input-font-size: 12px;
}
:deep(.t-button) {
  --td-button-height: 20px;
  --td-button-font-size: 12px;
}
.dialog-footer {
  padding: 10px;
  border-top: 1px solid #e0e0e0;
  background-color: #f5f5f5;
}
</style>